from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from myadmin import models
from myadmin.views.views_index import uploads
from django.contrib.auth.hashers import make_password, check_password
from django.core.paginator import Paginator
# Create your views here.
# 首页
def index(request):
    # 获取所有的一级分类
    data = models.category.objects.filter(pid=0)

    # 获取当前一级类下的二级分类
    for x in data:
        x.sub = models.category.objects.filter(pid=x.id)

        # 获取当前二级级类下的三级分类
        for y in x.sub:
            y.yub = models.category.objects.filter(pid=y.id)

    # # 判断用户是否登录
    # # 已登录
    # try:
    #     # 查询该用户未支付的商品,并在页面显示数量
    #     uid = request.session['VipUser']['uid']
    # except:
    #     pass

    # 分配数据
    context = {'data': data}
    # 加载首页
    return render(request, 'myhome/index.html', context)

#列表页
def goodslist(request):
    # 当前二级分类对象
    data = models.category.objects.get(id=request.GET.get('id'))

    # 当前二级分类 的子类
    ob = models.category.objects.filter(pid=data.id)

    # 数据分页
    allgoods = []
    # 如果有子类
    if ob.count() != 0:
        for g in ob:
            g.goodslist=models.goods.objects.filter(category_id=g).order_by(request.GET.get('orderby','id'))
            for goodsob in g.goodslist:
                allgoods.append(goodsob)

        new = ob.last()
        new.goodslist1 = models.goods.objects.filter(category_id=new).order_by(request.GET.get('orderby', 'id'))


        # 实例化分页类 参数1,获取的所有的数据对象   参数2 每页显示多少条
        paginator = Paginator(allgoods, 16)

        # 获取当前页码数  ?p=n
        p = request.GET.get('p', 1)

        # 获取当前页的数据
        glist = paginator.page(p)


        #分配数据
        context={'data':data,'list':glist,'new':new}

    else:
        data.goodslist = models.goods.objects.filter(category_id=data).order_by(request.GET.get('orderby', 'id'))

        # 实例化分页类 参数1,获取的所有的数据对象   参数2 每页显示多少条
        paginator = Paginator(data.goodslist, 8)
        print(data.goodslist)
        # 获取当前页码数  ?p=n
        p = request.GET.get('p', 1)

        # 获取当前页的数据
        glist = paginator.page(p)

        #分配数据
        context = {'data': data,'list':glist}
    # 加载模板
    return render(request, 'myhome/list.html',context)

# 商品搜索
def goodssearch(request):
    # 获取搜索关键字
    keywords = request.GET.get('keywords')
    # 判断是否有搜索关键字
    if keywords:
        # 商品分类名包含关键字
        cob = models.category.objects.filter(name__contains=keywords)
        if cob:
            from django.db.models import Q
            # 查询商品分类名包含关键字 且不是顶级分类的对象
            sdata = models.category.objects.get(Q(name__contains=keywords), Q(pid__gt=0))
            # 获取该分类下的全部商品对象
            sgoods = models.goods.objects.filter(category_id=sdata.id).order_by(request.GET.get('orderby', 'id'))

            # 如果sdata没有子类
            if len(sgoods)!=0:

                # 实例化分页类 参数1,获取的所有的数据对象   参数2 每页显示多少条
                paginator = Paginator(sgoods, 4)

                # 获取当前页码数  ?p=n
                p = request.GET.get('p', 1)

                # 获取当前页的数据
                slist = paginator.page(p)
                # 分配数据
                context = {'slist': slist, 'sname': keywords}
            elif len(sgoods)==0:
                glist = []
                for i in models.category.objects.filter(pid=sdata.id):
                    j=models.goods.objects.filter(category_id=i.id).order_by(request.GET.get('orderby', 'id'))
                    glist.append(j)

                # 实例化分页类 参数1,获取的所有的数据对象   参数2 每页显示多少条
                paginator = Paginator(glist, 4)

                # 获取当前页码数  ?p=n
                p = request.GET.get('p', 1)

                # 获取当前页的数据
                slist = paginator.page(p)
                # 分配数据
                context = {'slist': slist, 'sname': keywords,'condation':1}


        else:

            # 获取全部商品对象
            sgoods = models.goods.objects.all()
            # 按商品名称查询
            sgoods = sgoods.filter(name__contains=keywords).order_by(request.GET.get('orderby', 'id'))

            # 实例化分页类 参数1,获取的所有的数据对象   参数2 每页显示多少条
            paginator = Paginator(sgoods, 4)

            # 获取当前页码数  ?p=n
            p = request.GET.get('p', 1)

            # 获取当前页的数据
            slist = paginator.page(p)

            # 分配数据
            context = {'slist': slist, 'sname': keywords,'condation':2}

        # 加载列表页
        return render(request, 'myhome/slist.html', context)

# 详情页
def goodsinfo(request):
    # 接收商品id
    gid = request.GET.get('gid')
    lid = request.GET.get('lid')
    # 获取商品对象
    gob = models.goods.objects.get(id=gid)
    # 分配数据
    context = {'gob':gob,'lid':lid}
    # 加载详情页
    return render(request, 'myhome/info.html',context)


#购物车添加商品
def cartadd(request):
    # 获取购买商品对象
    bgoods = models.goods.objects.get(id=request.GET.get('gid'))
    # 获取购买数量
    bnum = int(request.GET.get('bnum'))

    # 获取购买商品用户对象
    buser = models.users.objects.get(id=request.session['VipUser']['uid'])

    # 判断该用户是否已添加过该商品进购物车
    try:
        sgoods = models.Cart.objects.get(uid=buser, goodsid=bgoods)

        sgoods.num += bnum
        sgoods.save()

    except:
        ob = models.Cart(uid=buser,goodsid=bgoods,num=bnum)
        ob.save()
    return JsonResponse({'error':0,'msg':"添加购物车成功"})

#购物车列表
def cartlist(request):

    # 获取当前用户的购物车数据
    data = models.Cart.objects.filter(uid=request.session['VipUser']['uid'])
    for i  in data:
        print(i.goodsid.id)

    # 分配数据
    context = {'data':data}

    # 加载页面
    return render(request,'myhome/cart.html',context)


# 购物车商品数量 修改
def cartedit(request):
    # 购物车id  数量
    cartid = request.GET.get('cartid')
    num = request.GET.get('num')

    # 获取购物车对象
    ob = models.Cart.objects.get(id=cartid)
    ob.num = int(num)
    ob.save()

    # 运算小计价格
    totalprice = ob.num * ob.goodsid.price

    return JsonResponse({'error': 0, 'msg': '修改成功', 'totalprice': "{:.2f}".format(totalprice)})

# 购物车商品删除
def cartdel(request):
    try:
        request.GET.get('delall')
        data = models.Cart.objects.filter(uid=request.session['VipUser']['uid'])
        data.delete()
    except:
        did = request.GET.get('did')
        delob = models.Cart.objects.get(goodsid=did)
        delob.delete()
    return JsonResponse({'error':0,'msg':"删除成功"})

# 订单确认
def orderconfirm(request):
    # 接收 cartids
    cartids = eval(request.GET.get('cartids'))

    # 获取对应的购物车数据
    data = models.Cart.objects.filter(id__in=cartids)

    # # 获取所有的一级城市数据
    citys = models.Citys.objects.filter(level=1)

    # 分配数据
    context = {'data': data, 'citys': citys}

    # 加载模板
    return render(request, 'myhome/confirm.html',context)


# 返回城市数据
def getcitys(request):
    # 根据id获取下一级的城市数据,返回json
    data = models.Citys.objects.filter(upid=request.GET.get('id')).values()

    # 解析json  返回
    return JsonResponse(list(data), safe=False)


# 收货地址获取
def addresslist(request):
    try:
        from django.db.models import Q
        # 获取设为默认地址多收货地址对象
        ob = models.Address.objects.get(Q(id=request.GET.get('lid')), Q(uid=request.session['VipUser']['uid']))
        # 状态设置为True
        ob.isChecked = 1
        ob.save()
        otherob = models.Address.objects.filter(uid=request.session['VipUser']['uid']).exclude(
            id=request.GET.get('lid'))
        # 其他地址设为False
        for i in otherob:
            print(i)
            i.isChecked = 0
            i.save()
    except:
        try:
            # 获取当前用户的所有收货地址
            data = models.Address.objects.filter(uid=request.session['VipUser']['uid']).values()

            for x in data:
                x['province'] = models.Citys.objects.get(id=x['province']).name
                x['city'] = models.Citys.objects.get(id=x['city']).name
                x['county'] = models.Citys.objects.get(id=x['county']).name
            #返回数据
            return JsonResponse({'error':0,'data':list(data)},safe=False)
        except:
            return JsonResponse({'error':1,'msg':'当前用户没有收货地址'})


# 收货地址添加
def addressadd(request):
        # 接收地址信息
        data = request.GET.dict()
        # 获取当前用户对象
        data['uid'] = models.users.objects.get(id=request.session['VipUser']['uid'])
        # 进行数据存储
        ob = models.Address(**data)
        ob.save()
        # 返回结果
        return JsonResponse({'aa': 1})

# 生成订单
def ordercreate(request):
    # 接收订单确认页数据
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')

    # 获取用户对象
    buser = models.users.objects.get(id=request.session['VipUser']['uid'])
    # 拼接收货地址
    addrid = models.Address.objects.get(id=data['re-addr'])
    province =models.Citys.objects.get(id=addrid.province).name
    city =models.Citys.objects.get(id=addrid.city).name
    county =models.Citys.objects.get(id=addrid.county).name
    info =addrid.info
    re_addr = province+city+county+info

    # 订单总价
    totalprice = 0
    # 购物车商品
    cart = models.Cart.objects.filter(id__in=eval(data['cartids']))
    for i in cart:
        totalprice += i.num*i.goodsid.price

    # 订单数据
    order_data={"uid":buser,"buser":addrid.buser,"buser_phone":addrid.buser_phone,"re_addr":re_addr,"payment":data['payment'],"logistics":data['logistics'],"totalprice":totalprice}
    # 生成订单
    ob_order = models.Order(**order_data)
    ob_order.save()

    # 订单详情
    for i in cart:
        orderinfo =models.OrderInfo()
        orderinfo.orderid = ob_order
        orderinfo.goodsid = i.goodsid.id
        orderinfo.name = i.goodsid.name
        orderinfo.price = i.goodsid.price
        orderinfo.pic_url = i.goodsid.pic_url
        orderinfo.num = i.num
        # 保存订单详情
        orderinfo.save()

        # 删除购物车中已生成订单商品
        i.delete()


    # 进入支付页
    return HttpResponse('<script>alert("订单创建成功,请前往支付");location.href="/order/pay/?orderid=' + str(ob_order.id) + '"</script>')

# 订单支付页面
def orderpay(request):
    # 订单号
    orderid = request.GET.get('orderid')

    return HttpResponse('<script>alert("支付成功,即将前往订单管理页面");location.href="' + reverse('myhome_myinfo_order') + '"</script>')

# 我的订单
def myinfo_order(request):
    # 获取当前用户
    user = models.users.objects.get(id=request.session['VipUser']['uid'])
    #当前用户所有订单
    allorder = user.order_set.all().order_by('-id')
    # 未付款订单
    nupayorder =user.order_set.filter(status=0).order_by('-id')
    # 计算未付款订单总价
    nupayprice =0
    for i in nupayorder:
        nupayprice += i.totalprice

    # 未发货订单
    unexpress =user.order_set.filter(status=1).order_by('-id')

    # 待收货订单
    unreceive =user.order_set.filter(status=2).order_by('-id')

    # 待评价订单
    judge = user.order_set.filter(status=3).order_by('-id')

    # 分配数据
    context = {'allorder':allorder,"nupayorder":nupayorder,"nupayprice":nupayprice,
               "unexpress":unexpress,"unreceive":unreceive,"judge":judge}

    # 加载模板
    return render(request,'myhome/myinfo/order.html',context)

# 个人中心
def myinfo(request):
    # # 获取当前用户
    # user = models.users.objects.get(id=request.session['VipUser']['uid'])
    #
    # # 分配数据
    # context = {'user':user}

    # 加载模板
    return render(request,'myhome/myinfo/index.html')
# 个人信息
def myinfo_userinfo(request):
    # 获取当前用户

    if request.method =='GET':
        user = models.users.objects.get(id=request.session['VipUser']['uid'])
        # 获取用户密码 并解密
        # from django.contrib.auth.hashers import make_password, check_password
        # upass = make_password(request.POST['password'], None, 'pbkdf2_sha256')
        # upass = check_password('1234567', 'pbkdf2_sha256$36000$197nqXM6yxYv$Zxh/Vsns8qszkvUmY81BgrjCeLPXhCHLEilP6VO+Rnc=')
        # 分配数据
        context = {'user':user}

        # 加载模板
        return render(request,'myhome/myinfo/user.html',context)
    else:
        # 接收修改后个人信息
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        print(data)
        # 获取用户对象
        user = models.users.objects.get(id=request.session['VipUser']['uid'])
        user.name =data['name']
        user.nickname = data['nickname']
        user.sex = data['sex']
        user.age = data['age']
        user.phone = data['phone']
        user.email = data['email']
        # 如果修改了密码
        if data['password2'] != '':
            # 密码加密
            from django.contrib.auth.hashers import make_password, check_password
            upass = make_password(data['password2'], None, 'pbkdf2_sha256')
            user.password = upass
        else:
            pass
        # 判断是否修改了头像
        myfile = request.FILES.get('Headpic')
        print(myfile)
        if myfile:
            # 调用函数进行头像上传
            user.Headpic = uploads(myfile)
        else:
            pass

        user.save()
        context={'user':user}
        return render(request,'myhome/myinfo/user.html',context)

# 我的收货地址
def myinfo_address(request):
    if request.method=="POST":
        user = models.users.objects.get(id=request.session['VipUser']['uid'])
        # 接收新增地址信息
        udata = request.POST.dict()
        udata.pop('csrfmiddlewaretoken')
        udata['uid'] = user
        # 新增地址实例化 保存
        naddr = models.Address(**udata)
        naddr.save()
        return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myhome_myinfo_address')+'"</script>')
    elif request.method=="GET":
        try:
            from django.db.models import Q
            # 获取设为默认地址多收货地址对象
            ob = models.Address.objects.get(Q(id=request.GET.get('id')), Q(uid=request.session['VipUser']['uid']))
            # 状态设置为True
            ob.isChecked = 1
            ob.save()
            otherob = models.Address.objects.filter(uid=request.session['VipUser']['uid']).exclude(id=request.GET.get('id'))
            # 其他地址设为False
            for i in otherob:
                print(i)
                i.isChecked = 0
                i.save()
        except:
            # 获取当前用户对象
            user = models.users.objects.get(id=request.session['VipUser']['uid'])
            # 获取当前用户所有收货地址
            data = models.Address.objects.filter(uid=request.session['VipUser']['uid']).values()
            for x in data:
                x['province'] = models.Citys.objects.get(id=x['province']).name
                x['city'] = models.Citys.objects.get(id=x['city']).name
                x['county'] = models.Citys.objects.get(id=x['county']).name

            # 获取省级城市数据
            pcity=models.Citys.objects.filter(upid=0)
            # 分配数据
            context = {'data':data,"user":user,'pcity':pcity}
        return render(request,'myhome/myinfo/address.html',context)




def login(request):
    # 获取登录前路由及参数
    nextpath = request.GET.get('nextpath','/')
    args = eval(request.GET.get('args',"{}"))

    a=""
    for k,v in args.items():
        a +='&'+k+'='+v
    #拼接路由
    nexturl = nextpath+'?'+a


    if request.method == 'GET':
        return render(request, 'myhome/login.html')

    else:
        # 执行登录
        try:
            # 先根据手机号获取用户,
            ob = models.users.objects.get(phone=request.POST['phone'])
            # 在对比密码是否正确
            res = check_password(request.POST['password'], ob.password)
            if res:
                # 用户名和密码都正确
                # 在session中存入登录凭证
                request.session['VipUser'] = {'nickname':ob.nickname,'vname': ob.name, 'phone': ob.phone, 'uid': ob.id,'pic_url': ob.Headpic}
                # 跳转到登录前页面
                return HttpResponse('<script>alert("登录成功");location.href="' + nexturl + '"</script>')
            else:
                # 密码错误
                pass
        except:
            pass
            # 用户名不存在

        return HttpResponse('<script>alert("用户名或密码错误");location.href="' + reverse('myhome_login') + '"</script>')


def logout(request):
    del request.session['VipUser']

    return HttpResponse('<script>alert("退出登录");location.href="/";</script>')


def register(request):
    if request.method == 'GET':
        return render(request, 'myhome/register.html')
    else:
        try:
            # 验证手机号和验证码是否和session中一致
            if request.POST['phone'] != request.session['msgcode']['phone'] or request.POST['code'] != \
                    request.session['msgcode']['code']:
                return HttpResponse(
                    '<script>alert("注册失败,验证码不正确");location.href="' + reverse('myhome_register') + '"</script>')

            # 密码加密
            password = make_password(request.POST['password'], None, 'pbkdf2_sha256')
            # 生成随机的用户名
            username = 'user' + str(request.POST['phone'])
            data = {'name': username, 'phone': request.POST['phone'], 'password': password}
            print(data)
            # 执行注册
            ob = models.users(**data)
            ob.save()
            # 跳转登录页面
            return HttpResponse('<script>alert("注册成功.请登录");location.href="' + reverse('myhome_login') + '"</script>')
        except:
            return HttpResponse('<script>alert("注册失败");location.href="' + reverse('myhome_register') + '"</script>')


# 验证手机号
def checkphone(request):
    # 接受手机号
    phone = request.GET.get('phone')
    # 到数据库查询
    num = models.users.objects.filter(phone=phone).count()

    if num:
        return JsonResponse({'error': 1, 'msg': '手机号码已存在'})
    else:
        return JsonResponse({'error': 0, 'msg': '手机号码不存在'})


# 手机短信验证码发送
def sendmsg(request):
    # 接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
    # 账户注册：请通过该地址开通账户http://user.ihuyi.com/register.html
    # 注意事项：
    # （1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
    # （2）请使用 用户名 及 APIkey来调用接口，APIkey在会员中心可以获取；
    # （3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；

    # import urllib2
    import urllib
    import urllib.request
    import json
    import random
    # 用户名 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
    account = "C08111534"
    # 密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
    password = "4f2db76276519dd8ecfe1c97bd23a9bb"
    # 接受注册页面提供的手机号
    mobile = request.GET.get('phone')
    # 随机验证码
    code = str(random.randint(10000, 99999))
    print(code)
    # 把验证码存入session
    request.session['msgcode'] = {'phone': mobile, 'code': code}
    # text = "您的验证码是："+code+"。请不要把验证码泄露给其他人。"
    # data = {'account': account, 'password' : password, 'content': text, 'mobile':mobile,'format':'json' }
    # # 发起 请求
    # req = urllib.request.urlopen(
    #     url= 'http://106.ihuyi.com/webservice/sms.php?method=Submit',
    #     data= urllib.parse.urlencode(data).encode('utf-8')
    # )
    # # 获取响应内容
    # content =req.read()
    # # 解析结果
    # res = json.loads(content.decode('utf-8'))
    # print(res)
    return HttpResponse('aa')



